from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import os
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

# 数据库类型配置 (sqlite, mysql, postgresql等)
DB_TYPE = os.getenv("DB_TYPE", "sqlite")

# SQLite配置
DB_PATH = os.getenv("DB_PATH", "./campus_map.db")

# MySQL/PostgreSQL配置
DB_HOST = os.getenv("DB_HOST", "localhost")
DB_PORT = os.getenv("DB_PORT", "3306")
DB_USER = os.getenv("DB_USER", "root")
DB_PASSWORD = os.getenv("DB_PASSWORD", "")
DB_NAME = os.getenv("DB_NAME", "campus_map_db")

# 构建数据库URL
if DB_TYPE.lower() == "sqlite":
    DATABASE_URL = f"sqlite:///{DB_PATH}"
    # SQLite特定连接参数
    connect_args = {"check_same_thread": False}
else:
    # MySQL或PostgreSQL连接URL
    if DB_TYPE.lower() == "mysql":
        driver = "pymysql"
    elif DB_TYPE.lower() == "postgresql":
        driver = "psycopg2"
    else:
        driver = "pymysql"  # 默认使用MySQL
    
    DATABASE_URL = f"{DB_TYPE}+{driver}://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
    connect_args = {}

# 创建数据库引擎
engine = create_engine(DATABASE_URL, connect_args=connect_args)

# 创建会话工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 创建基础模型类
Base = declarative_base()

# 获取数据库会话
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
